package com.example.server.util;

import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.UUID;

public class Util {

    /**
     * @param multipartFile
     * @param directory
     * @return "test.jpg"
     */
    public static String savePicture(MultipartFile multipartFile, String directory) {
        File path = new File(directory); // 上传文件存放的位置
        String extension = StringUtils.getFilenameExtension(multipartFile.getOriginalFilename()); // 扩展名  png, jpg, ...
        String filename = UUID.randomUUID() + "." + extension; // 重定义唯一文件名
        try {
            multipartFile.transferTo(new File(path, filename)); // 保存文件
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return filename;
    }

    /**
     *
     * @param multipartFiles
     * @param directory
     * @return "[\"1.jpg\", \"2.png\"]"
     */
    public static String savePicture(MultipartFile[] multipartFiles, String directory) {
        String[] filenames = new String[multipartFiles.length];
        for (int i = 0; i < multipartFiles.length; i++) {
            filenames[i] = "\"" + savePicture(multipartFiles[i], directory) + "\"";
        }
        return Arrays.toString(filenames);
    }

    /**
     *
     * @param nickname
     * @return encrypted nickname
     */
    public static String encryptNickname(String nickname) {
        if (nickname.length() > 5) {
            return nickname.charAt(0) + "****" + nickname.charAt(nickname.length() - 1);
        } else {
            return nickname.charAt(0) + "****";
        }
    }
}
